<template>
  <view>
    <scroll-view scroll-y class="scroll_box" :style="{ height: `calc(100vh - ${bottomHeight}px)` }">
      <!-- 骨架屏 -->
      <skeleton v-if="showSkeleton"></skeleton>
      <view v-else>
        <!-- 商品图片 -->
        <view class="uni-margin-wrap">
          <swiper class="swiper" circular :current="currentIndex" @change="onChange">
            <swiper-item v-for="item in goodsDetailInfo.mainPictures" :key="item">
              <view class="swiper-item">
                <image :src="item" style="width: 100%; height: 100%" @click="clickImage(item)" />
              </view>
            </swiper-item>
          </swiper>
          <!-- 指示器 -->
          <view class="dot"
            >{{ currentIndex + 1 }}/{{ (goodsDetailInfo.mainPictures || []).length }}</view
          >
        </view>
        <!-- 商品基础信息 -->
        <view class="base_box">
          <!-- 价格 -->
          <view class="price_box">
            <!-- 最新价格 -->
            ￥<text class="text">{{ goodsDetailInfo.price }}</text>
            <!-- 老价格 -->
            <text
              style="
                margin-left: 10rpx;
                text-decoration: line-through;
                color: rgba(255, 255, 255, 0.7);
                font-size: 26rpx;
              "
              >￥{{ goodsDetailInfo.oldPrice }}</text
            >
          </view>
          <!-- 标题 -->
          <view class="title_box">{{ goodsDetailInfo.name }}</view>
          <!-- 描述 -->
          <view class="desc_box">{{ goodsDetailInfo.desc }}</view>
          <!-- 选择商品规格 -->
          <view class="common_box" @click="openSpec(1)">
            <text class="text">选择</text>请选择商品规格</view
          >
          <!-- 选择收货地址 -->
          <view class="common_box" @click="openAddress">
            <text class="text">送至</text><text v-if="!addressInfo.id">请选择收货地址</text
            ><text v-else>{{ addressInfo.fullLocation + addressInfo.address }}</text></view
          >
          <!-- 服务 -->
          <view class="common_box" style="border-bottom: 0" @click="openService">
            <text class="text">服务</text>退货运费险 极速退款 7天无理由退换</view
          >
        </view>
        <!-- 商品详情信息 -->
        <view class="detail_box">
          <view class="header_box">详情</view>
          <view
            class="common_box"
            v-for="item in (goodsDetailInfo.details || {}).properties"
            :key="item.name"
          >
            <view class="frist">{{ item.name }}</view>
            <view style="flex: 1">{{ item.value }}</view>
          </view>
          <!-- 图片 -->
          <view class="proudct-item-area">
            <!-- 每张图片 -->
            <image
              v-for="item in (goodsDetailInfo.details || {}).pictures"
              :key="item"
              :src="item"
              mode="widthFix"
              style="width: 100%; height: auto"
            />
          </view>
        </view>
        <!-- 同类推荐 -->
        <view class="peer_box">
          <view class="header_box" style="margin-bottom: 20rpx">同类推荐</view>
          <!-- 商品 -->
          <view class="goods_box">
            <!-- 每个商品 -->
            <view class="goods_item" v-for="item in goodsDetailInfo.similarProducts" :key="item.id">
              <navigator
                :url="`/pages/goodsDetail/goodsDetail?id=${item.id}`"
                style="width: 100%; height: 100%"
              >
                <image :src="item.picture" class="image" />
                <view>{{ item.name }}</view>
                <view class="price_box">￥{{ item.price }}</view>
              </navigator>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <!-- 用户操作 -->
    <view class="toolbar" :style="{ paddingBottom: bottomHeight + 'px' }">
      <view class="icons">
        <button class="icons-button"><text class="icon-heart"></text>收藏</button>
        <!-- #ifdef MP-WEIXIN -->
        <button class="icons-button" open-type="contact">
          <text class="icon-handset"></text>客服
        </button>
        <!-- #endif -->

        <navigator class="icons-button" url="/pages/cart2/cart2">
          <text class="icon-cart"></text>购物车
        </navigator>
      </view>
      <view class="buttons">
        <view class="addcart" @click="openSpec(2)"> 加入购物车 </view>
        <view class="buynow" @click="openSpec(3)"> 立即购买 </view>
      </view>
    </view>
    <!-- sku规格弹出层 -->
    <spec ref="specRef" :goodsInfo="goodsInfo"></spec>
    <!-- 服务弹出层 -->
    <service ref="serviceRef"></service>
    <!-- 收货地址弹出层 -->
    <addressPopup ref="addressRef" @getAddress="getAddress"></addressPopup>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
// 引入接口函数
import { getAddressListAPI } from '@/api/address'
import { getGoodsDetailByIdAPI } from '@/api/goodsDetail'
// 引入ts类型
import type { goodsDetailType, goodsInfoType } from '@/types/goodsDetail'
// 引入子组件
import spec from './components/spec.vue'
import service from './components/service.vue'
import addressPopup from './components/addressPopup.vue'
import skeleton from './components/skeleton.vue'
import type { addressInfoType } from '@/types/address'
// 显示骨架屏
const showSkeleton = ref(true)
// 获取页面栈
const pages = getCurrentPages()
// 商品规格的ref对象
const specRef = ref()
// 服务弹出层的ref对象
const serviceRef = ref()
// 收货地址的ref对象
const addressRef = ref()
const app = uni.getSystemInfoSync()
const bottomHeight = app.safeAreaInsets!.bottom //屏幕底部安全距离
// 当前所在滑块的 index
const currentIndex = ref(0)
// 轮播图改变时的回调
const onChange = (e: any) => {
  currentIndex.value = e.detail.current
}
// 获取页面传递过来的商品id
const query = defineProps<{
  id: string
}>()
// 商品详情对象
const goodsDetailInfo = ref<goodsDetailType>({} as goodsDetailType)
// 商品规格对象
const goodsInfo = ref<goodsInfoType>({} as goodsInfoType)
// 获取商品详情数据的函数
const getGoodsDetailData = async () => {
  // 显示骨架屏
  showSkeleton.value = true
  const res = await getGoodsDetailByIdAPI(query.id)
  if (res.code === '1') {
    goodsDetailInfo.value = res.result
    // 整理商品规格数据，使其符合插件的数据格式
    goodsInfo.value._id = goodsDetailInfo.value.id
    goodsInfo.value.name = goodsDetailInfo.value.name
    goodsInfo.value.goods_thumb = goodsDetailInfo.value.mainPictures[0]
    goodsInfo.value.sku_list = goodsDetailInfo.value.skus.map((item) => {
      return {
        _id: item.id,
        goods_id: goodsDetailInfo.value.id,
        goods_name: goodsDetailInfo.value.name,
        image: item.picture,
        price: Number(item.price) * 100,
        sku_name_arr: item.specs.map((item1) => item1.valueName),
        stock: item.inventory,
      }
    })
    goodsInfo.value.spec_list = goodsDetailInfo.value.specs.map((item) => {
      return {
        list: item.values.map((item1) => {
          return {
            name: item1.name,
          }
        }),
        name: item.name,
      }
    })
    // 隐藏骨架屏
    showSkeleton.value = false
  }
}
// 打开商品规格
const openSpec = (mode: number) => {
  specRef.value.open(goodsInfo.value, mode, addressInfo.value.id!)
}
// 打开服务弹出层
const openService = () => {
  serviceRef.value.open()
}
// 打开收货地址弹出层
const openAddress = () => {
  addressRef.value.open(addressList.value, addressInfo.value.id)
}
// 点击图片的回调
const clickImage = (url: string) => {
  // 预览图片的方法
  uni.previewImage({
    urls: goodsDetailInfo.value.mainPictures, // 需要预览图片的http列表
    current: url, // 当前显示图片的http链接，默认是第一个
    // 成功的回调
    // success: (success) => {
    //   console.log(success)
    // },
  })
}
// 地址列表
const addressList = ref<addressInfoType[]>([] as addressInfoType[])
// 地址信息
const addressInfo = ref<addressInfoType>({} as addressInfoType)
// 定义一个变量，用来记录地址接口获取了多少次
const count = ref(0)
// 获取地址列表
const getAddressList = async () => {
  const res = await getAddressListAPI()
  count.value++
  if (res.code === '1') {
    addressList.value = res.result
    const temp = addressList.value.find((item) => item.isDefault === 1)
    if (temp) {
      addressInfo.value = temp
    }
    if (count.value > 1) {
      // 多次获取了接口，证明是新建地址后重新返回页面， 重新打开弹出层
      addressRef.value.open(addressList.value, addressInfo.value.id)
    }
  }
}
// 接收弹出层传递过来的地址信息
const getAddress = (data: { address: addressInfoType; id: string }) => {
  addressInfo.value = data.address
  addressInfo.value.id = data.id
}
onLoad(() => {
  getGoodsDetailData()
  getAddressList()
})
onShow(() => {
  if (pages[pages.length - 2].$vm.$mp) {
    if (pages.length > 1) {
      pages[pages.length - 2].$vm.$mp.text = ''
    }
    if (pages[0].$vm.$mp.text === '新建地址') {
      getAddressList()
    }
  }
})
</script>

<style lang="scss">
@font-face {
  font-family: 'iconfont';
  src:
    url('http://at.alicdn.com/t/c/font_4107366_cexjwxv31th.woff2?t=1707219411908') format('woff2'),
    url('http://at.alicdn.com/t/c/font_4107366_cexjwxv31th.woff?t=1707219411908') format('woff'),
    url('http://at.alicdn.com/t/c/font_4107366_cexjwxv31th.ttf?t=1707219411908') format('truetype');
}
.scroll_box {
  overflow-y: scroll;
  background-color: #f4f4f4;
  margin-bottom: 60rpx;
  .uni-margin-wrap {
    position: relative;
    width: 100%;
    .swiper {
      height: 700rpx;
    }
    .swiper-item {
      display: block;
      height: 700rpx;
      line-height: 700rpx;
      text-align: center;
    }
    .swiper-list {
      margin-top: 40rpx;
      margin-bottom: 0;
    }
    .uni-common-mt {
      margin-top: 60rpx;
      position: relative;
    }
    .info {
      position: absolute;
      right: 20rpx;
    }
    .uni-padding-wrap {
      width: 550rpx;
      padding: 0 100rpx;
    }
    .dot {
      position: absolute;
      right: 20rpx;
      bottom: 20rpx;
      display: inline;
      padding: 5rpx 20rpx;
      background-color: rgba(0, 0, 0, 0.3);
      font-size: 24rpx;
      color: #fff;
      border-radius: 22rpx;
    }
  }
  .base_box {
    background-color: #fff;
    margin-bottom: 20rpx;
    .price_box {
      padding-left: 20rpx;
      height: 120rpx;
      line-height: 120rpx;
      background-color: #ff0034;
      color: #fff;
      .text {
        font-size: 48rpx;
      }
    }
    .title_box {
      margin: 20rpx 0;
      padding-left: 20rpx;
      font-size: 32rpx;
    }
    .desc_box {
      padding: 0 0 20rpx 20rpx;
      font-size: 22rpx;
      color: #ff0034;
      border-bottom: 1px solid #eee;
    }
    .common_box {
      height: 100rpx;
      line-height: 100rpx;
      font-size: 28rpx;
      margin-left: 20rpx;
      border-bottom: 1px solid #eee;
      .text {
        color: #999;
        margin: 0 20rpx 0 0;
      }
    }
    .common_box::after {
      font-family: 'iconfont';
      content: '\e629';
      float: right;
      margin-right: 20rpx;
      color: #999;
    }
  }
  .detail_box {
    margin-bottom: 20rpx;
    background-color: #fff;
    font-size: 28rpx;
    .common_box {
      display: flex;
      padding: 20rpx 20rpx 20rpx 0;
      margin-left: 20rpx;
      border-bottom: 1px dashed #eee;
      .frist {
        width: 230rpx;
      }
    }
    .proudct-item-area {
      margin: 0 10px;
      border-radius: 8px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
    }
  }
  .header_box {
    position: relative;
    background-color: #fff;
    height: 100rpx;
    line-height: 100rpx;
    font-weight: 700;
    padding-left: 30rpx;
    &::after {
      position: absolute;
      top: 50%;
      margin-top: -15rpx;
      left: 20rpx;
      content: '';
      display: inline-block;
      width: 4rpx;
      height: 30rpx;
      background-color: #ff0034;
    }
  }
  .peer_box {
    font-size: 28rpx;
    .goods_box {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      margin: 0 20rpx;
      .goods_item {
        position: relative;
        flex: 48%;
        background-color: #fff;
        box-sizing: border-box;
        margin-bottom: 20rpx;
        box-sizing: border-box;
        border-radius: 10rpx;
        padding: 16rpx;
        height: 460rpx;
        font-size: 26rpx;
        .image {
          width: 310rpx;
          height: 310rpx;
        }
        .price_box {
          position: absolute;
          bottom: 10rpx;
          left: 10rpx;
          color: #d14c4c;
        }
      }
      .goods_item:nth-child(odd) {
        margin-right: 10rpx;
      }
      .goods_item:nth-child(even) {
        margin-left: 10rpx;
      }
    }
  }
}
/* 底部工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx var(--window-bottom);
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;
  .buttons {
    display: flex;
    & > view {
      width: 220rpx;
      text-align: center;
      line-height: 72rpx;
      font-size: 26rpx;
      color: #fff;
      border-radius: 72rpx;
    }
    .addcart {
      background-color: #ffa868;
    }
    .buynow,
    .payment {
      background-color: #ff0034;
      margin-left: 20rpx;
    }
  }
  .icons {
    padding-right: 10rpx;
    display: flex;
    align-items: center;
    flex: 1;
    .icons-button {
      flex: 1;
      text-align: center;
      line-height: 1.4;
      padding: 0;
      margin: 0;
      border-radius: 0;
      font-size: 20rpx;
      color: #333;
      background-color: #fff;
      &::after {
        border: none;
      }
    }
    text {
      display: block;
      font-size: 34rpx;
    }
  }
}
/* #ifdef APP-PLUS || H5*/
.navigator-wrap {
  flex: 1;
}
/* #endif */
</style>
